﻿var API_Address = "http://tt.czwgl.com";
if (document.domain.indexOf("localhost") >= 0) {
    API_Address = "http://localhost:44382";
}
var API_Bearer = "";
var bearer = window.localStorage.getItem("API_Bearer");
if (IsVaild(bearer)) { API_Bearer = bearer; }

//写cookies
function setCookie(name, value, Days) {
    if (IsNullOrEmpty(Days)) Days = 7;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;";
}
//读取cookies 
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

//ajax
var defaultInfo = {
    //type: "GET",                        //访问方式：如果dataPata不为空，自动设置为POST；如果为空设置为GET。
    dataType: "JSON",      //数据类型：JSON、JSONP、text。由配置信息来搞定，便于灵活设置
    cache: false,                        //是否缓存，默认缓存  不使用缓存 缓存有可能造成数据不刷新
    async: true,
    crossDomain: true,
    contentType: "application/json",
    xhrFields: {
        //允许跨域访问时添加cookie。cors跨域的时候需要设置
        withCredentials: true
    },
    showLoading: true,
    Lock: false,
    //data: {},//表单里的参数。如果dataType是JSON，一定加在form里，不会加在url后面；如果dataType是JSONP的话，只能加在url后面。

    //url:"",  //依靠上层指定

    timeout: 20000,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.toast(textStatus + ":" + errorThrown);
    },  //如果出错，停止加载动画，给出提示。也可以增加自己的处理程序

    success: function (data) {
        if (data.Status == 1) {
            $.toast(data.Message);
        }
        else {
            $.toast(data.Message);
        }
    },
    complete: function (XMLHttpRequest, textStatus) { },

};
function ajax(ajaxInfo) {

    if (ajaxInfo.data != undefined && ajaxInfo.type == undefined) {
        ajaxInfo.type = "POST";
    } else if (ajaxInfo.type != "POST") {
        ajaxInfo.type = "GET";
    }
    ajaxInfo = $.extend({}, defaultInfo, ajaxInfo);

    if (defaultInfo.Lock && !ajaxInfo.showLoading) return;

    if (ajaxInfo.url.indexOf("http") < 0) {
        ajaxInfo.url = API_Address + ajaxInfo.url;
    }
    //开始执行ajax
    $.ajax({
        type: ajaxInfo.type,
        dataType: ajaxInfo.dataType,
        cache: ajaxInfo.cache,
        xhrFields: ajaxInfo.xhrFields,
        async: ajaxInfo.async,
        contentType: ajaxInfo.contentType,
        url: ajaxInfo.url,
        data: JSON.stringify(ajaxInfo.data),
        headers: { "Authorization": API_Bearer },
        crossDomain: ajaxInfo.crossDomain,
        beforeSend: function () {
            if (typeof ajaxInfo.beforeSend == "function") {
                ajaxInfo.beforeSend();
            }
            if (ajaxInfo.showLoading)
                $.showLoading();

            if (!ajaxInfo.showLoading) {
                defaultInfo.Lock = true;
            }
        },
        timeout: ajaxInfo.timeout,
        error: function (data) { //访问失败，自动停止加载动画，并且给出提示

            var reload = false;
            if (IsVaild(data.status)) { //如果身份认证失败,重新登录
                if (data.status == 401 || data.status == 302) {
                    if (ajaxInfo.url.indexOf("RefreshToken") < 0)
                        window.location.href = '/index';
                }
            }
            if (typeof ajaxInfo.error == "function" && !reload) {
                ajaxInfo.error(data);
            }
        },
        success: function (data) {
            ajaxInfo.success(data);
        },
        complete: function (XMLHttpRequest, textStatus) {
            if (!ajaxInfo.showLoading) {
                defaultInfo.Lock = false;
            }
            if (typeof ajaxInfo.complete == "function") {
                ajaxInfo.complete(XMLHttpRequest, textStatus);
            }

            if (ajaxInfo.showLoading)
                $.hideLoading();

        }
    });
}

//返回json对象
function returnJsonFromdata(data) {
    var json = null;
    try { json = eval("(" + data + ")"); }
    catch (ex) { try { json = eval(data); } catch (e) { } }
    return json;
}

//获取url传参
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
    var r;
    if (window.location.href.indexOf("?") < 0) {
        r = window.location.search.substr(1).match(reg);
    }
    else {
        if (window.location.search.substr(1).indexOf("=") >= 0) { r = (window.location.search.substr(1)).match(reg); }
        else
            r = decodeURIComponent(window.location.search.substr(1)).match(reg);  //匹配目标参数  
    }
    if (r != null) return unescape(r[2]); return ""; //返回参数值  
}

//日期格式化
Date.prototype.DateFormat = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
String.prototype.FormatDate = function (format) {
    if (IsNullOrEmpty(format)) format = "yyyy-MM-dd";
    var f = datetimeParse(this, format);
    return f;
}
function datetimeParse(str, format) {
    if (str == null || str == undefined) return "";
    var d = eval('new ' + str.substr(1, str.length - 2));
    return d.Format(format);
}
//转换为小数点
String.prototype.FormatFloat = function (fixed) {
    var f = parseFloat(this);
    if (isNaN(f)) {
        return 0;
    }
    return f.toFixed(fixed);
}

//判断字符串是否为空
function IsVaild(str) {
    if (str != undefined && str != null && str != "")
        return true;
    else return false;
}
function IsNullOrEmpty(str) {
    if (str != undefined && str != null && str != "")
        return false;
    else return true;
}






//放在最后,如果小于10分钟刷新token
var Token_Expired = window.localStorage.getItem("Token_Expired");
if (IsVaild(Token_Expired) && window.location.href.indexOf("/index") < 0) {

    if ((new Date(Token_Expired) - new Date()) / 60000 < 10) {
        ajax({
            url: API_Address + "/User/RefreshToken",
            type: "Get",
            success: function (data) {
                window.localStorage.setItem("API_Bearer", "Bearer " + data.data.tokenContent);
                window.localStorage.setItem("Token_Expired", data.data.expires);
            },
        });
    }
}